package com.avecsys.quotemanager.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.jsf.FacesContextUtils;

import com.avecsys.quotemanager.constants.ApplicationConstants;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.pojos.SupplierUsersPojo;
import com.avecsys.quotemanager.pojos.UserMasterPojo;
import com.avecsys.quotemanager.service.supplier.QuoteTemplateMasterService;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.UIComponentUtils;
import com.avecsys.quotemanager.vo.SupplierVO;
import com.icesoft.faces.component.ext.HtmlInputHidden;

/**
 * Validator Component to Check the Quote Template Name is unqiue for a supplier. The check ignores the
 * case
 * 
 * @author Sam Sundar K
 */
public class ValidatorSupplierQuoteTemplateNameUnique extends BaseValidator
{
	private static final Log log = LogFactory.getLog(ValidatorSupplierQuoteTemplateNameUnique.class);

	public FacesMessage validateFieldValue(FacesContext facesContext, UIComponent uIComponent,
			Object object) throws ValidatorException
	{
		String uicomponentQuoteTemplateNameId = (String) object;
		QuoteTemplateMasterService quoteTemplateMasterService = (QuoteTemplateMasterService) FacesContextUtils.getWebApplicationContext(
				facesContext)
				.getBean("quoteTemplateMasterService");
		FacesMessage message = new FacesMessage();
		SupplierVO supplierVO = new SupplierVO();
		HtmlInputHidden uicomponentTemplateId = (HtmlInputHidden) uIComponent.getParent().findComponent(
				"templateID");
		if (!UIComponentUtils.isValueEmpty(uicomponentTemplateId))
		{
			supplierVO.setTemplateId(new Long(uicomponentTemplateId.getValue().toString()));
		}
		supplierVO.setTemplateName(uicomponentQuoteTemplateNameId);
		UserMasterPojo userMasterPojo = (UserMasterPojo) FacesContext.getCurrentInstance()
				.getExternalContext()
				.getSessionMap()
				.get(ApplicationConstants.SESSION_USER);
		for (SupplierUsersPojo supplierUsersPojo : userMasterPojo.getSupplierUsersPojo())
		{
			supplierVO.setSupplierMasterPojo(supplierUsersPojo.getSupplierMasterPojo());
		}
		try
		{
			if (!quoteTemplateMasterService.isQuoteTemplateNameUnique(supplierVO))
			{
				message.setSummary(MessageBoardUtil.getValue(
						facesContext,
							ApplicationConstants.RESOURCE_BUNDLE_SUPPLIER,
							ApplicationConstants.VALIDATOR_ERROR_SUPPLIER_QUOTE_TEMPLATE_NAME_NOT_UNIQUE,
							null));
			}
		}
		catch (BusinessException e)
		{
			log.error(e);
		}
		return message;
	}
}
